package com.drojian.side.service;


import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.widget.RemoteViews;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import com.drojian.demo.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class NotificationServiceMusic extends Service{
    private static final String CHANNEL_ID = "song_play_channel";
    // 定义一个前台serviceId
    public static final int FOREGROUND_ID = 1;
    private List<Integer> musicList;
    private MediaPlayer player;
    private RemoteViews remoteView;
    private Notification notification;
    private NotificationManager notificationManager;
    private int currentMusicIndex = 0;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        musicList = new ArrayList<>();
        musicList.add(R.raw.music1);
        musicList.add(R.raw.music2);
        musicList.add(R.raw.music3);
        musicList.add(R.raw.music4);
        musicList.add(R.raw.music5);
        player = new MediaPlayer();
        // 广播注册
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(GlobalConstants.ACTION_CLOSE_MUSIC);
        intentFilter.addAction(GlobalConstants.ACTION_NEXT_MUSIC);
        intentFilter.addAction(GlobalConstants.ACTION_PRE_MUSIC);
        intentFilter.addAction(GlobalConstants.ACTION_PLAY_PAUSE_MUSIC);
        registerReceiver(mReceiver, intentFilter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getStringExtra("action");
        switch (action) {
            case "notification":
                playMusic();
                break;
        }
        createNotification();
        return super.onStartCommand(intent, flags, startId);
    }
        private void createNotification(){
            notificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "音乐播放通知", NotificationManager.IMPORTANCE_LOW);
                notificationManager.createNotificationChannel(channel);
            }
            // 自定义通知中的内容View
            remoteView = new RemoteViews(getPackageName(), R.layout.part3_notification_music_layout);
            // 设置通知中的TextView文字
            remoteView.setTextViewText(R.id.notification_text, "歌曲的名字");
            // 点击通知中内容View中的子View，发出广播
            // 下一曲
            Intent nextIntent = new Intent(GlobalConstants.ACTION_NEXT_MUSIC);
            PendingIntent nextPendIntent = PendingIntent.getBroadcast(this, 0, nextIntent, PendingIntent.FLAG_IMMUTABLE);
            remoteView.setOnClickPendingIntent(R.id.iv_next, nextPendIntent);
            // 上一曲
            Intent preIntent = new Intent(GlobalConstants.ACTION_PRE_MUSIC);
            PendingIntent prePendIntent = PendingIntent.getBroadcast(this, 0, preIntent, PendingIntent.FLAG_IMMUTABLE);
            remoteView.setOnClickPendingIntent(R.id.iv_previous, prePendIntent);
            // 暂停、播放
            Intent playPauseIntent = new Intent(GlobalConstants.ACTION_PLAY_PAUSE_MUSIC);
            PendingIntent playPausePendIntent = PendingIntent.getBroadcast(this, 0, playPauseIntent, PendingIntent.FLAG_IMMUTABLE);
            remoteView.setOnClickPendingIntent(R.id.iv_play_pause, playPausePendIntent);
            // 关闭音乐
            Intent closeIntent = new Intent(GlobalConstants.ACTION_CLOSE_MUSIC);
            PendingIntent closePendIntent = PendingIntent.getBroadcast(this, 0, closeIntent, PendingIntent.FLAG_IMMUTABLE);
            remoteView.setOnClickPendingIntent(R.id.iv_cancel, closePendIntent);

            notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setSmallIcon(android.R.drawable.ic_media_play)
                    .setCustomContentView(remoteView)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), android.R.drawable.ic_media_pause))
                    .build();

            startForeground(FOREGROUND_ID, notification);
        }
        private BroadcastReceiver mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                switch (intent.getAction()) {
                    case GlobalConstants.ACTION_CLOSE_MUSIC:
                        stopForeground(true);
                        stopSelf();
                        break;
                    case GlobalConstants.ACTION_PRE_MUSIC:
                        previousMusic();
                        break;
                    case GlobalConstants.ACTION_NEXT_MUSIC:
                        nextMusic();
                        break;
                    case GlobalConstants.ACTION_PLAY_PAUSE_MUSIC:
                        if(player != null && player.isPlaying()){
                            player.pause();
                        }else {
                            player.start();
                        }
                        break;
                }
            }
        };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.release();
            player = null;
        }
        unregisterReceiver(mReceiver);
    }
    private void playMusic() {
        if (player.isPlaying()) {
            player.stop();
            player.reset();
        }

        try {
            int resourceId = musicList.get(currentMusicIndex);
            player.setDataSource(this, Uri.parse("android.resource://" + getPackageName() + "/" + resourceId));
            player.prepare();
            player.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void nextMusic() {
        currentMusicIndex = (currentMusicIndex + 1) % musicList.size(); // 循环到列表的下一项
        playMusic(); // 播放下一首音乐
    }
    private void previousMusic() {
        currentMusicIndex = (currentMusicIndex - 1 + musicList.size()) % musicList.size(); // 循环到列表的上一项
        playMusic(); // 播放上一首音乐
    }

}

